package com.iwhalecloud.bss.kite.cucc.web.controller.batch;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.cart.common.constant.KiteCartErrorConsts;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.batch.IBatchConfigService;
import com.iwhalecloud.bss.kite.cucc.client.dto.batch.KiteBatchConfig;
import com.iwhalecloud.bss.kite.manager.transaction.KiteTransactional;
import com.ztesoft.bss.base.annotation.IgnoreSession;
import com.ztesoft.bss.common.util.ContextUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 批量受理
 */
@RestController
@RequestMapping("/batchAcceptTemp")
@Api(tags = {
    "/batchAcceptTemp - 极简批量受理-模版配置"
})
public class LocalBatchAcceptTempController {

    @Autowired
    private IBatchConfigService localBatchAcceptTempService;

    @ApiOperation(value = "查询配置模板", notes = "查询配置模板")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "query", value = "查询条件"),
    })
    @PostMapping("/queryKiteBatchConfig")
    public DataResult<PageInfo<KiteBatchConfig>> queryKiteBatchConfig(@RequestBody Map<String, Object> query) {
        if (KiteStringUtils.isEmpty(KiteMapUtils.getString(query, "createStaffCode"))) {
            query.put("createStaff", String.valueOf(ContextUtil.getLoginInfo().getStaffInfo().getStaffId()));
        }
        if (KiteStringUtils.isEmpty(KiteMapUtils.getString(query, "applyRegionCode"))) {
            query.put("applyRegionCode", ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
        }
        // 根据文件名模糊查询标识
        query.put("likeSearch", true);
        return KiteCartErrorConsts.SUCCESS.getResult(localBatchAcceptTempService.queryKiteBatchConfig(query));
    }

    @ApiOperation(value = "查询配置模板", notes = "查询配置模板")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "query", value = "查询条件"),
    })
    @PostMapping("/queryKiteBatchConfigForList")
    public DataResult<List<KiteBatchConfig>> queryKiteBatchConfigForList(@RequestBody Map<String, Object> query) {
        return KiteCartErrorConsts.SUCCESS.getResult(localBatchAcceptTempService.queryKiteBatchConfigForList(query));
    }

    @ApiOperation(value = "更新配置模板", notes = "更新配置模板")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "param", value = "参数"),
    })
    @PostMapping("/updateKiteBatchConfig")
    public DataResult<String> updateKiteBatchConfig(@RequestBody KiteBatchConfig kiteBatchConfig) {
        return localBatchAcceptTempService.updateKiteBatchConfig(kiteBatchConfig);
    }

    @ApiOperation(value = "删除配置模板", notes = "删除配置模板")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "configId", value = "模板id参数"),
    })
    @PostMapping("/deleteKiteBatchConfig")
    public DataResult<String> updateKiteBatchConfig(@RequestParam String configId) {
        return localBatchAcceptTempService.deleteKiteBatchConfig(configId);
    }

    @ApiOperation(value = "保存配置模板", notes = "保存配置模板")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "KiteBatchConfig", value = "参数")
    })
    @PostMapping("/saveKiteBatchConfig")
    public DataResult<String> saveKiteBatchConfig(@RequestBody KiteBatchConfig kiteBatchConfig) {
        kiteBatchConfig.setCreateStaff(ContextUtil.getLoginInfo().getStaffInfo().getStaffId());
        kiteBatchConfig.setCreateStaffCode(ContextUtil.getLoginInfo().getStaffInfo().getStaffCode());
        return localBatchAcceptTempService.saveKiteBatchConfig(kiteBatchConfig);
    }

    @KiteTransactional
    @ApiOperation(value = "批量模板导入", notes = "批量模板导入")
    @PostMapping(produces = "application/json;charset=utf-8", value = "/batchImport")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "file", value = "file", required = true, dataType = "file", paramType = "form"),
        @ApiImplicitParam(name = "goodsSku", value = "商品id")
    })
    public DataResult<Map<String, Object>> batchImport(@RequestParam(value = "file") MultipartFile file, @RequestParam String goodsSku) throws Exception {

        String fileName = file.getOriginalFilename();
        String fileType = KiteStringUtils.substring(fileName, fileName.lastIndexOf('.') + 1);
        if (!KiteStringUtils.equalsAny(fileType, "xls", "xlsx")) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("只允许上传excel格式文件");
        }
        boolean isXls = "xls".equals(fileName.substring(fileName.lastIndexOf('.') + 1));

        return localBatchAcceptTempService.batchImport(file.getInputStream(), file.getInputStream(), isXls, fileName, goodsSku);
    }

    @ApiOperation(value = "查询产品属性", notes = "查询产品属性")
    @ApiImplicitParams( {
        @ApiImplicitParam(name = "goodsSku", value = "goodsSku"),
    })
    @PostMapping("/getProdAttr")
    public DataResult<List<Map<String, Object>>> getProdAttr(@RequestParam String goodsSku) {
        return KiteCartErrorConsts.SUCCESS.getResult(localBatchAcceptTempService.getProdAttr(goodsSku));
    }

    @ApiOperation(value = "下载配置模版", notes = "下载配置模版")
    @GetMapping(value = "/downloadTemplate")
    @IgnoreSession
    public DataResult<Boolean> downloadTemplate(String configId, HttpServletResponse response) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("configId", configId);
            List<KiteBatchConfig> configs = localBatchAcceptTempService.queryKiteBatchConfigForList(map);
            if (KiteListUtils.isEmpty(configs)) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("模板不存在，请检查配置");
            }
            KiteBatchConfig kiteBatchConfig = configs.get(0);
            String fileName = kiteBatchConfig.getTmplFileName();
            String fileType = KiteStringUtils.substring(fileName, fileName.lastIndexOf('.') + 1);
            if (!KiteStringUtils.equalsAny(fileType, "xls", "xlsx")) {
                fileName = fileName + ".xls";
            }
            //通知浏览器以附件形式下载
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition",
                "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            localBatchAcceptTempService.exportExcel(response.getOutputStream(), kiteBatchConfig);
        }
        catch (Exception e) {
            return ErrorConsts.BUSI_COMMON_ERROR.getResult(Boolean.TRUE, e.getMessage());
        }
        return ErrorConsts.SUCCESS.getResult(Boolean.TRUE);
    }

    @ApiOperation(value = "预览配置模版", notes = "预览配置模版")
    @GetMapping(value = "/previewTemplate")
    public DataResult<Boolean> previewTemplate(String configId, HttpServletResponse response) {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("configId", configId);
            List<KiteBatchConfig> configs = localBatchAcceptTempService.queryKiteBatchConfigForList(map);
            if (KiteListUtils.isEmpty(configs)) {
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("模板不存在，请检查配置");
            }
            KiteBatchConfig kiteBatchConfig = configs.get(0);
            localBatchAcceptTempService.previewTemplate(response.getOutputStream(), kiteBatchConfig);
        }
        catch (Exception e) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut(e.getMessage());
        }
        return ErrorConsts.SUCCESS.getResult(Boolean.TRUE);
    }
}
